<template>
  <div class="app-container">
    <!-- 显示已选筛选条件 -->
    <div class="active-filters">
      <div class="filter-tags">
        <span>当前筛选条件：</span>
        <el-tag v-for="(filter, index) in activeFilters" :key="index" closable @close="removeFilter(filter.column)">
          {{ filter.text }}
        </el-tag>
        <el-button v-if="hasActiveFilters" type="text" @click="clearAllFilters" size="small">清除所有</el-button>
      </div>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:productFailureInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:productFailureInfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-import" size="mini" @click="handleImport('importData')"
          v-hasPermi="['product:productInfo:importData']">导入失效数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-import" size="mini" @click="handleImport('importDataDetail')"
          v-hasPermi="['product:productInfo:importDataDetail']">导入失效明细信息</el-button>
      </el-col>
      <right-toolbar :search="false" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table border stripe v-loading="loading" :data="productFailureInfoList" @selection-change="handleSelectionChange"
      :header-cell-class-name="headerCellClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="55" type="index" />
      <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
        :min-width="column.width" show-overflow-tooltip align="center">
        <template slot="header" slot-scope="scope">
          <el-popover placement="bottom" width="300" trigger="manual" v-model="column.showFilter"
            :close-on-click-modal="false" popper-class="custom-popover" @show="handlePopoverShow(column)">
            <div class="filter-content">
              <div v-if="column.filterType === 'text'">
                <el-input v-model="column.tempFilterValue" placeholder="请输入筛选内容"
                  @keyup.enter.native="applyFilters(column)"></el-input>
              </div>

              <!-- 选择器筛选 -->
              <div v-if="column.filterType === 'select'">
                <el-select v-model="column.tempFilterValue" placeholder="请选择" style="width: 100%" multiple>
                  <el-option v-for="item in column.options" :key="item.value" :label="item.label"
                    :value="item.label"></el-option>
                </el-select>
              </div>

              <!-- 日期范围筛选 -->
              <div v-if="column.filterType === 'daterange'">
                <el-date-picker v-model="column.tempFilterValue" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%"
                  value-format="yyyy-MM-dd"></el-date-picker>
              </div>
              <div v-if="column.filterType === 'year'">
                <el-date-picker v-model="column.tempFilterValue" type="year" format="yyyy" value-format="yyyy"
                  style="width: 100%" placeholder="选择年">
                </el-date-picker>
              </div>
              <div v-if="column.filterType === 'month'">
                <el-date-picker v-model="column.tempFilterValue" type="month" format="yyyy-MM" value-format="yyyy-MM"
                  style="width: 100%" placeholder="选择月">
                </el-date-picker>
              </div>

              <div class="filter-footer">
                <el-button type="primary" size="small" @click="applyFilters(column)">确定</el-button>
                <el-button size="small" @click="cancelFilter(column)">取消</el-button>
              </div>
            </div>

            <div slot="reference" class="header-cell" @click.stop="toggleFilter(column)">
              <span>{{ column.label }}</span>
              <i class="el-icon-arrow-down filter-icon" :class="{ 'active-filter': hasFilterValue(column) }"></i>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:productFailureInfo:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['product:productFailureInfo:remove']">删除</el-button>
          <el-button size="mini" type="text" @click="handleAnnex(scope.row)"
            v-hasPermi="['product:productFailureInfo:file']">附件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改产品叶片失效信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-dialogDrag width="910px" append-to-body
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :inline="true" class="addData">
        <!--   filterable
            @change="selectProjectdata" -->
        <el-form-item label="关联项目" prop="projectId">
          <el-select filterable remote :remote-method="searchProject" v-model="form.projectId"
            @change="selectProjectdata" clearable popper-class="select-with-pagination">
            <el-option v-for="item in failureList" :key="item.id" :value="item.id"
              :label="item.drawingNumber + '--' + item.projectName" />

            <!-- 自定义下拉底部内容 -->
            <div slot="prefix" class="custom-prefix"></div>
            <!-- 修复选项被遮挡的补丁 -->
            <div slot="empty" v-if="failureList.length === 0" class="empty">
              暂无数据
            </div>

            <!-- 分页组件（放在下拉面板底部） -->
            <div class="pagination-footer">
              <el-pagination small @current-change="handlePageChange" :current-page="pagination.currentPage"
                :page-size="pagination.pageSize" :total="pagination.total" layout="prev, pager, next,total"
                :pager-count="5" />
            </div>
          </el-select>
        </el-form-item>
        <el-form-item label="图号" prop="drawingNumber">
          <el-input v-model="form.drawingNumber" placeholder="请输入图号" />
        </el-form-item>
        <el-form-item label="机型" prop="productModel">
          <el-input v-model="form.productModel" placeholder="请输入机型" />
        </el-form-item>
        <el-form-item label="产品级数" prop="productStageCount">
          <el-input v-model="form.productStageCount" placeholder="请输入产品级数" />
        </el-form-item>
        <el-form-item label="产品编号" prop="productSerialNumber">
          <el-input v-model="form.productSerialNumber" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="事故版本号" prop="accidentVersion">
          <el-input v-model="form.accidentVersion" placeholder="请输入事故版本号" />
        </el-form-item>
        <el-form-item label="主轴轴头号" prop="shaftHeadNumber">
          <el-input v-model="form.shaftHeadNumber" placeholder="请输入主轴轴头号" />
        </el-form-item>
        <el-form-item label="用户" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户" />
        </el-form-item>
        <el-form-item label="工质" prop="productMedium">
          <el-input v-model="form.productMedium" placeholder="请输入工质" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="投运时间" prop="operationStartYear">
          <el-date-picker v-model="form.operationStartYear" type="year" format="yyyy" value-format="yyyy"
            placeholder="请选择投运时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效时间" prop="failureDate">
          <el-date-picker v-model="form.failureDate" type="month" format="yyyy-MM" value-format="yyyy-MM"
            placeholder="请选择失效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="运行时长" prop="runningDuration">
          <el-input v-model="form.runningDuration" placeholder="请输入运行时长" />
        </el-form-item>
        <el-form-item label="失效类型" prop="failureTypes">
          <el-select v-model="failureTypes" placeholder="请选择失效类型" multiple>
            <el-option v-for="dict in typeList" :key="dict.value" :label="dict.label" :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="失效总级数" prop="totalFailureStages">
          <el-input v-model="form.totalFailureStages" placeholder="请输入失效总级数" />
        </el-form-item>
        <el-form-item label="失效总叶片数(枚)" prop="totalFailureBlades">
          <el-input v-model="form.totalFailureBlades" placeholder="请输入失效总叶片数" />
        </el-form-item>
        <el-form-item label="流道拐点级号" prop="flowChannelInflectionStages">
          <el-input v-model="form.flowChannelInflectionStages" placeholder="请输入流道拐点级号" />
        </el-form-item>
        <el-form-item label="失效原因归类" prop="failureReasons">
          <el-select v-model="failureReasons" placeholder="请选择失效原因归类" multiple>
            <el-option v-for="dict in reasonList" :key="dict.value" :label="dict.label" :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分析时间" prop="reportDates">
          <el-date-picker v-model="form.reportDates" type="month" format="yyyy-MM" value-format="yyyy-MM"
            placeholder="请选择失效时间">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="分析报告" prop="hasAnalysisReport">
              <file-upload v-model="form.hasAnalysisReport" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="失效分析单位" prop="analysisInstitutes">
              <el-input v-model="form.analysisInstitutes" type="textarea" placeholder="请输入失效分析单位" maxlength="300"
                show-word-limit rows="5" style="width: 700px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="改进措施" prop="improvementMeasures">
              <el-input style="width: 700px" v-model="form.improvementMeasures" type="textarea" placeholder="请输入改进措施"
                maxlength="300" show-word-limit rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="失效情况描述" prop="failureDescription">
              <el-input style="width: 700px" v-model="form.failureDescription" type="textarea" placeholder="请输入失效情况描述"
                maxlength="300" show-word-limit rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="结论" prop="conclusions">
              <el-input style="width: 700px" v-model="form.conclusions" type="textarea" placeholder="请输入结论"
                maxlength="300" show-word-limit rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="改进措施说明" prop="detailedImprovements">
              <el-input style="width: 700px" v-model="form.detailedImprovements" type="textarea" placeholder="请输入改进措施说明"
                maxlength="300" show-word-limit rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input style="width: 700px" v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="100"
                show-word-limit rows="5" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">叶片失效明细信息</el-divider>
        <div style="
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
            margin-right: 20px;
          ">
          <el-button type="primary" icon="el-icon-plus" size="mini"
            @click="handleAddTProductFailureDetail">添加</el-button>
        </div>
        <el-table :data="form.tproductFailureDetailList" :row-class-name="rowTProductFailureDetailIndex"
          ref="tProductFailureDetail" max-height="300" border>
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="失效级号" prop="failureStage" min-width="150" show-overflow-tooltip align="center">
          </el-table-column>
          <el-table-column label="失效叶片类型" prop="bladeType" min-width="150" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="失效型式" prop="failureMode" align="center" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="失效位置" align="center" prop="failurePositions" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="失效叶片数(枚)" align="center" prop="bladeFailureCount" min-width="150"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="失效叶片图号" align="center" prop="bladeDrawingNumber" min-width="150"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="失效叶片材料" prop="bladeMaterial" align="center" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="性能等级" prop="bladeGrade" align="center" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="同级叶片总数" align="center" prop="totalBladeCount" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="叶根型式" prop="rootType" align="center" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="弦长 (mm)" align="center" prop="chordLengthMm" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="叶高 (mm)" align="center" prop="bladeHeightMm" min-width="150" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleUpdateRecord(scope.row)">修改</el-button>
              <el-button size="mini" type="text" @click="handleDeleteRecord(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="失效叶片信息记录" :visible.sync="recordOpen" :close-on-click-modal="false" width="900px" append-to-body
      v-dialogDrag>
      <el-form ref="recordform" :model="recordform" label-width="120px" :inline="true" class="addData">
        <el-form-item label="失效级号" prop="failureStage">
          <el-input v-model="recordform.failureStage" placeholder="请输入失效级号" />
        </el-form-item>
        <el-form-item label="失效叶片类型" prop="bladeType">
          <el-select v-model="recordform.bladeType" placeholder="请选择失效类型">
            <el-option v-for="dict in typeList" :key="dict.value" :label="dict.label" :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="失效型式" prop="failureMode">
          <el-select v-model="recordform.failureMode" placeholder="请选择失效型式">
            <el-option v-for="dict in dict.type.systemshape" :key="dict.value" :label="dict.label"
              :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="失效位置" prop="failurePositions">
          <el-select v-model="failurePositions" placeholder="请选择失效位置" multiple>
            <el-option v-for="dict in dict.type.systemposition" :key="dict.value" :label="dict.label"
              :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="失效叶片数(枚)" prop="bladeFailureCount">
          <el-input v-model="recordform.bladeFailureCount" placeholder="请输入失效叶片数" />
        </el-form-item>
        <el-form-item label="失效叶片图号" prop="bladeDrawingNumber">
          <el-input v-model="recordform.bladeDrawingNumber" placeholder="请输入失效叶片图号" />
        </el-form-item>
        <el-form-item label="失效叶片材料" prop="bladeMaterial">
          <el-input v-model="recordform.bladeMaterial" placeholder="请输入失效叶片材料" />
        </el-form-item>
        <el-form-item label="性能等级" prop="bladeGrade">
          <el-input v-model="recordform.bladeGrade" placeholder="请输入性能等级" />
        </el-form-item>
        <el-form-item label="同级叶片总数" prop="totalBladeCount">
          <el-input v-model="recordform.totalBladeCount" placeholder="请输入同级叶片总数" />
        </el-form-item>
        <el-form-item label="叶根型式" prop="rootType">
          <el-input v-model="recordform.rootType" placeholder="请输入叶根型式" />
        </el-form-item>
        <el-form-item label="弦长 (mm)" prop="chordLengthMm">
          <el-input v-model="recordform.chordLengthMm" placeholder="请输入弦长 (mm)" />
        </el-form-item>
        <el-form-item label="叶高 (mm)" prop="bladeHeightMm">
          <el-input v-model="recordform.bladeHeightMm" placeholder="请输入叶高 (mm)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormRecoed">确 定</el-button>
        <el-button @click="cancelRecord">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px"
      append-to-body v-dialogDrag>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  failureInfo,
  listProductFailureInfo,
  getProductFailureInfo,
  delProductFailureInfo,
  addProductFailureInfo,
  updateProductFailureInfo,
} from "@/api/product/productFailureInfo";
import { getToken } from "@/utils/auth";
import { dictList } from "@/api/select";
// 提取公共处理函数
const processDictData = (rows) => {
  return rows.map((item) => ({
    ...item,
    value: item.dictValue,
    label: item.dictLabel,
  }));
};
export default {
  name: "ProductFailureInfo",
  dicts: ["systemshape", "systemposition"],
  data() {
    return {
      loading: false,
      searchKeyword: '', // 存储搜索关键词
      // 用户导入参数
      upload: {
        type: "",
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/product/productFailureInfo/importData",
      },
      reasonList: [],
      typeList: [],
      columns: [
        {
          prop: "drawingNumber",
          label: "图号",
          width: "150",
          filterType: "text",
          filterValue: "", // 已确定的筛选值
          tempFilterValue: "", // 临时编辑的筛选值
          showFilter: false,
        },
        {
          prop: "productModel",
          label: "机型",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "productStageCount",
          label: "产品级数",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "productSerialNumber",
          label: "产品编号",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "accidentVersion",
          label: "事故版本号",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "shaftHeadNumber",
          label: "主轴轴头号",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "userName",
          label: "用户",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "productMedium",
          label: "工质",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "projectName",
          label: "项目名称",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "operationStartYear",
          label: "投运时间",
          width: "220",
          filterType: "year",
          filterValue: [],
          tempFilterValue: [],
          showFilter: false,
        },
        {
          prop: "failureDate",
          label: "失效时间",
          width: "220",
          filterType: "month",
          filterValue: [],
          tempFilterValue: [],
          showFilter: false,
        },
        {
          prop: "runningDuration",
          label: "运行时长",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "failureTypes",
          label: "失效类型",
          width: "180",
          filterType: "select",
          filterValue: [],
          tempFilterValue: [],
          showFilter: false,
          options: [
            { label: "研发部", value: "研发部" },
            { label: "市场部", value: "市场部" },
            { label: "人事部", value: "人事部" },
            { label: "财务部", value: "财务部" },
          ],
          // options:dict.type.failureTypes
        },
        {
          prop: "totalFailureStages",
          label: "失效总级数",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "totalFailureBlades",
          label: "失效总叶片数",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "flowChannelInflectionStages",
          label: "流道拐点级号",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "failureReasons",
          label: "失效原因归类",
          width: "180",
          filterType: "select",
          filterValue: [],
          tempFilterValue: [],
          showFilter: false,
          options: [
            { label: "研发部", value: "研发部" },
            { label: "市场部", value: "市场部" },
            { label: "人事部", value: "人事部" },
            { label: "财务部", value: "财务部" },
          ],
        },
        {
          prop: "improvementMeasures",
          label: "改进措施",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "hasAnalysisReport",
          label: "分析报告",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "failureDescription",
          label: "失效情况描述",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "reportDates",
          label: "分析时间",
          width: "220",
          filterType: "month",
          filterValue: [],
          tempFilterValue: [],
          showFilter: false,
        },
        {
          prop: "analysisInstitutes",
          label: "失效分析单位",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "conclusions",
          label: "结论",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "detailedImprovements",
          label: "改进措施说明",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
        {
          prop: "remark",
          label: "备注",
          width: "150",
          filterType: "text",
          filterValue: "",
          tempFilterValue: "",
          showFilter: false,
        },
      ],
      failureTypes: [],
      failureReasons: [],
      failurePositions: [],
      currentEditIndex: -1,
      recordform: {},
      recordOpen: false,
      pagination: {
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页条数
        total: 0, // 总数据量
      },
      // 查询未生成失效信息的产品数据
      failureList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTProductFailureDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品叶片失效信息表格数据
      productFailureInfoList: [],
      // 叶片失效明细表格数据
      tProductFailureDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      // queryParams: {
      //   pageNum: 1,
      //   pageSize: 10,
      //   projectId: null,
      //   drawingNumber: null,
      //   productModel: null,
      //   productStageCount: null,
      //   productSerialNumber: null,
      //   accidentVersion: null,
      //   shaftHeadNumber: null,
      //   userName: null,
      //   productMedium: null,
      //   projectName: null,
      //   operationStartYear: null,
      //   failureDate: null,
      //   runningDuration: null,
      //   failureTypes: null,
      //   totalFailureStages: null,
      //   totalFailureBlades: null,
      //   flowChannelInflectionStages: null,
      //   failureReasons: null,
      //   improvementMeasures: null,
      //   hasAnalysisReport: null,
      //   failureDescription: null,
      //   reportDates: null,
      //   analysisInstitutes: null,
      //   conclusions: null,
      //   detailedImprovements: null,
      // },
      // 表单参数
      form: {
        tproductFailureDetailList: [],
      },
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "关联项目不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // 并行请求两个字典数据
    Promise.all([
      dictList({ dictType: "systemtype" }),
      dictList({ dictType: "systemreason" }),
    ]).then(([typeRes, reasonRes]) => {
      // 处理并赋值类型列表
      this.typeList = processDictData(typeRes.rows);
      this.columns[12].options = this.typeList;

      // 处理并赋值原因列表
      this.reasonList = processDictData(reasonRes.rows);
      this.columns[16].options = this.reasonList;
    });
    this.getList();
    this.fetchFailureList(); // 初始化加载第一页数据
  },
  computed: {
    // 已激活的筛选条件（已点击确定的）
    activeFilters() {
      const filters = [];
      this.columns.forEach((column) => {
        if (this.hasFilterValue(column)) {
          let text = "";
          if (
            (column.filterType === "text" && column.filterValue) ||
            (column.filterType === "year" && column.filterValue.length > 0) ||
            (column.filterType === "month" && column.filterValue.length > 0)
          ) {
            text = `${column.label}: ${column.filterValue}`;
          } else if (
            column.filterType === "select" &&
            column.filterValue.length > 0
          ) {
            const selectedOptions = column.options
              .filter((opt) => column.filterValue.includes(opt.label))
              .map((opt) => opt.label)
              .join(", ");
            text = `${column.label}: ${selectedOptions}`;
          } else if (
            column.filterType === "daterange" &&
            column.filterValue.length === 2
          ) {
            text = `${column.label}: ${column.filterValue[0]} 至 ${column.filterValue[1]}`;
          }

          if (text) {
            filters.push({
              column: column.prop,
              text: text,
            });
          }
        }
      });
      return filters;
    },

    // 是否有激活的筛选条件
    hasActiveFilters() {
      return this.activeFilters.length > 0;
    },

    // 构建查询参数（使用已确定的filterValue）
    queryParams() {
      const params = {};
      (params.pageNum = 1),
        (params.pageSize = 10),
        this.columns.forEach((column) => {
          if (this.hasFilterValue(column)) {
            params[column.prop] = column.filterValue;
          }
        });
      return params;
    },
  },
  methods: {
    handleAnnex(row) {
      this.$router.push({
        path: "/attachment/attachmentUpload",
        query: {
          projectId: row.projectId,
          fileType: 1
          // queryParams: JSON.stringify(this.queryParams),
          // paths: "/product/productInfo",
        },
      });
    },
    /** 导入按钮操作 */
    handleImport(type) {
      this.upload.title =
        type == "importData" ? "导入失效数据" : "导入失效明细信息";
      this.upload.open = true;
      this.upload.type = type;
      this.upload.url =
        type == "importData"
          ? process.env.VUE_APP_BASE_API +
          "/product/productFailureInfo/importData"
          : process.env.VUE_APP_BASE_API +
          "/product/productFailureInfo/importDataDetail";
    },
    /** 下载模板操作 */
    importTemplate() {
      let url =
        this.upload.type == "importData"
          ? "/product/productFailureInfo/importTemplate"
          : "/product/productFailureInfo/importTemplateDetail";
      this.download(url, {}, `${this.upload.type == "importData" ? '导入失效数据模板' : '导入失效明细信息模板'}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.upload.updateSupport = 0;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 判断列是否有筛选值（使用已确定的filterValue）
    hasFilterValue(column) {
      if (column.filterType === "daterange") {
        return column.filterValue && column.filterValue.length === 2;
      } else if (
        column.filterType === "select" ||
        column.filterType === "year" ||
        column.filterType === "month"
      ) {
        return column.filterValue && column.filterValue.length > 0;
      }
      return (
        column.filterValue !== "" &&
        column.filterValue !== null &&
        column.filterValue !== undefined
      );
    },

    // 切换筛选框显示状态
    toggleFilter(column) {
      // 关闭其他所有筛选框
      this.columns.forEach((col) => {
        if (col.prop !== column.prop) {
          col.showFilter = false;
        }
      });

      // 初始化临时筛选值为当前已确定的筛选值
      if (column.filterType === "daterange") {
        column.tempFilterValue = column.filterValue.length
          ? [...column.filterValue]
          : [];
      } else if (column.filterType === "select") {
        column.tempFilterValue = [...column.filterValue];
      } else {
        column.tempFilterValue = column.filterValue;
      }
      column.showFilter = !column.showFilter;
    },
    handlePopoverShow(column) {
      // 确保只有一个 popover 显示
      this.columns.forEach((col) => {
        if (col.prop !== column.prop) {
          col.showFilter = false;
        }
      });
    },
    // 应用筛选（点击确定）
    applyFilters(column) {
      // 将临时值赋给正式筛选值
      if (column.filterType === "daterange") {
        column.filterValue = column.tempFilterValue.length
          ? [...column.tempFilterValue]
          : [];
      } else if (column.filterType === "select") {
        column.filterValue = [...column.tempFilterValue];
      } else {
        column.filterValue = column.tempFilterValue;
      }

      // 关闭弹窗
      column.showFilter = false;

      // 调用接口获取数据
      this.getList();
    },

    // 取消筛选（点击取消）
    cancelFilter(column) {
      // 不保存临时值，直接关闭弹窗
      column.showFilter = false;
    },

    // 移除单个筛选条件
    removeFilter(columnProp) {
      const column = this.columns.find((col) => col.prop === columnProp);
      if (column) {
        if (column.filterType === "daterange") {
          column.filterValue = [];
        } else if (column.filterType === "select") {
          column.filterValue = [];
        } else {
          column.filterValue = "";
        }
        // 重新获取数据
        this.getList();
      }
    },

    // 清除所有筛选条件
    clearAllFilters() {
      this.columns.forEach((column) => {
        if (column.filterType === "daterange") {
          column.filterValue = [];
        } else if (column.filterType === "select") {
          column.filterValue = [];
        } else {
          column.filterValue = "";
        }
        column.showFilter = false;
      });
      // 重新获取数据
      this.getList();
    },
    // 表头单元格类名
    headerCellClassName() {
      return "table-header-center";
    },
    async selectProjectdata(selectedId) {
      if (!selectedId) {
        this.form.drawingNumber = "";
        this.form.productModel = "";
        this.form.productStageCount = "";
        this.form.userName = "";
        this.form.productMedium = "";
        this.form.projectName = "";
        return;
      }

      // 当前列表查找
      const selectedItem = this.failureList.find(
        (item) => item.id === selectedId
      );
      if (selectedItem) {
        this.form.drawingNumber = selectedItem.drawingNumber;
        this.form.productModel = selectedItem.productModel;
        this.form.productStageCount = selectedItem.productStageCount;
        this.form.userName = selectedItem.userName;
        this.form.productMedium = selectedItem.productMedium;
        this.form.projectName = selectedItem.projectName;
        return;
      }
      // 如果没有，调用API获取
      failureInfo({
        id: selectedId,
      }).then((res) => {
        this.currentDrawingNumber = res.drawingNumber;
      });
    },

    async fetchFailureList(searchKeyword) {
      failureInfo({
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        drawingNumber: searchKeyword
      }).then((res) => {
        this.failureList = res.rows || [];
        this.pagination.total = res.total;
      }).catch(() => {
        this.failureList = [];
        this.pagination.total = 0;
      });
    },
    handlePageChange(page) {
      this.pagination.currentPage = page;
      this.fetchFailureList(this.searchKeyword);
    },
    // 远程搜索方法
    async searchProject(keyword) {
      this.loading = true;
      this.searchKeyword = keyword; // 更新搜索词

      // 重置到第一页（重要！）
      this.pagination.currentPage = 1;
      this.fetchFailureList(this.searchKeyword);
    },
    /** 查询产品叶片失效信息列表 */
    getList() {
      this.productFailureInfoList = [];
      this.loading = true;
      listProductFailureInfo(this.queryParams).then((response) => {
        this.productFailureInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        drawingNumber: null,
        productModel: null,
        productStageCount: null,
        productSerialNumber: null,
        accidentVersion: null,
        shaftHeadNumber: null,
        userName: null,
        productMedium: null,
        projectName: null,
        operationStartYear: null,
        failureDate: null,
        runningDuration: null,
        failureTypes: null,
        totalFailureStages: null,
        totalFailureBlades: null,
        flowChannelInflectionStages: null,
        failureReasons: null,
        improvementMeasures: null,
        hasAnalysisReport: null,
        failureDescription: null,
        reportDates: null,
        analysisInstitutes: null,
        conclusions: null,
        detailedImprovements: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
      };
      this.form.tproductFailureDetailList = [];
      this.failureTypes = [];
      this.failureReasons = [];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品叶片失效信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProductFailureInfo(id).then((response) => {
        this.form = response.data;
        this.form.tproductFailureDetailList = this.form
          .tproductFailureDetailList
          ? this.form.tproductFailureDetailList
          : [];
        this.failureTypes = this.form.failureTypes.split(",");
        this.failureReasons = this.form.failureReasons.split(",");
        this.open = true;
        this.title = "修改产品叶片失效信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.failureTypes = this.failureTypes.join(",");
          this.form.failureReasons = this.failureReasons.join(",");
          if (this.form.id != null) {
            updateProductFailureInfo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductFailureInfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除产品叶片失效信息数据项？")
        .then(function () {
          return delProductFailureInfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 叶片失效明细序号 */
    rowTProductFailureDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 叶片失效明细添加按钮操作 */
    handleAddTProductFailureDetail() {
      this.recordOpen = true;
      this.currentEditIndex = -1;
      this.resetRecordform();
    },
    // 取消按钮
    cancelRecord() {
      this.recordOpen = false;
      this.currentEditIndex = -1;
      this.resetRecordform();
    },
    resetRecordform() {
      this.recordform = {
        id: null,
        failureStage: null,
        bladeType: null,
        failureMode: null,
        failurePositions: null,
        bladeFailureCount: null,
        bladeDrawingNumber: null,
        bladeMaterial: null,
        bladeGrade: null,
        totalBladeCount: null,
        rootType: null,
        chordLengthMm: null,
        bladeHeightMm: null,
      };
      this.failurePositions = [];
      this.resetForm("recordform");
    },
    // 生成临时ID
    generateTempId() {
      return "temp_" + Date.now() + Math.floor(Math.random() * 1000);
    },
    // 判断两行数据是否相同
    isSameRow(row1, row2) {
      const keys = Object.keys(row1);
      return keys.every((key) => row1[key] === row2[key]);
    },
    // 提交失效明细
    submitFormRecoed() {
      this.$refs.recordform.validate((valid) => {
        if (valid) {
          const formData = { ...this.recordform };
          if (!this.form.tproductFailureDetailList) {
            this.form.tproductFailureDetailList = [];
          }
          formData.failurePositions = this.failurePositions.join(",");
          if (this.currentEditIndex === -1) {
            // 新增操作
            if (!formData.id) {
              formData.temp_id = this.generateTempId(); // 为新增数据生成临时ID
            }

            this.form.tproductFailureDetailList.push(formData);
          } else {
            // 修改操作
            if (formData.id) {
              // 根据ID修改
              const index = this.form.tproductFailureDetailList.findIndex(
                (item) => item.id === formData.id
              );
              if (index !== -1) {
                this.form.tproductFailureDetailList.splice(index, 1, formData);
              }
            } else {
              // 没有ID，根据行数据匹配修改
              this.form.tproductFailureDetailList.splice(
                this.currentEditIndex,
                1,
                formData
              );
            }
          }
          this.recordOpen = false;
          this.resetRecordform();
        }
      });
    },

    // 修改失效明细
    handleUpdateRecord(row) {
      this.failurePositions = row.failurePositions.split(",");
      this.recordOpen = true;
      this.recordform = { ...row };

      // 查找当前编辑项的索引
      if (row.id) {
        this.currentEditIndex = this.form.tproductFailureDetailList.findIndex(
          (item) => item.id === row.id
        );
      } else {
        this.currentEditIndex = this.form.tproductFailureDetailList.findIndex(
          (item) => this.isSameRow(item, row)
        );
      }
    },

    // 删除失效明细
    handleDeleteRecord(row) {
      this.$confirm("确认删除失效明细?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.id) {
            // 根据ID删除
            const index = this.form.tproductFailureDetailList.findIndex(
              (item) => item.id === row.id
            );
            if (index !== -1) {
              this.form.tproductFailureDetailList.splice(index, 1);
            }
          } else {
            // 没有ID，根据索引删除
            const index = this.form.tproductFailureDetailList.findIndex(
              (item) => this.isSameRow(item, row)
            );
            if (index !== -1) {
              this.form.tproductFailureDetailList.splice(index, 1);
            }
          }
          this.$message.success("删除成功!");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/productFailureInfo/export",
        {
          ...this.queryParams,
        },
        `productFailureInfo_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .addData {
  .el-input {
    width: 280px !important;
  }
}

/* 修复下拉面板滚动条问题 */
.select-with-pagination {
  .el-select-dropdown__wrap {
    max-height: 300px !important;
    /* 限制下拉框高度 */
    padding-bottom: 40px;
    /* 为分页留出空间 */
  }
}

// /* 分页底部定位 */
// .pagination-footer {
//   position: absolute;
//   bottom: 0;
//   left: 0;
//   right: 0;
//   padding: 8px 15px;
//   background: white;
//   border-top: 1px solid #e4e7ed;
//   z-index: 10;
// }
.empty {
  padding: 10px 0;
  font-size: 14px;
  color: #999;
  text-align: center;
}

// /* 修复选项被分页遮挡的问题 */
.custom-prefix {
  height: 0;
  visibility: hidden;
}

::v-deep .el-table .table-header-center {
  text-align: center;

  .cell {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
  }
}

.header-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  cursor: pointer;

  >span {
    margin-right: 6px;
  }

  .filter-icon {
    font-size: 14px;
    color: #c0c4cc;
    transition: all 0.3s;

    &.active-filter {
      color: #0275cd;
    }
  }

  &:hover .filter-icon {
    color: #0275cd;
  }
}

.filter-content {
  padding: 10px;

  >div {
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .filter-footer {
    margin-top: 10px;
    text-align: right;
  }
}

.active-filters {
  margin-bottom: 15px;
  padding: 12px;
  background-color: #f8fbff;
  border-radius: 4px;
  border: 1px solid #f8fbff;

  .filter-tags {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;

    >span {
      font-size: 14px;
      color: #606266;
    }

    .el-tag {
      margin-right: 8px;
    }

    .el-button {
      margin-left: 10px;
    }
  }
}

::v-deep .el-table {
  th {
    background-color: #f8f8f9;
  }

  td {
    padding: 8px 0;
  }

  .el-table__body-wrapper {
    overflow-x: auto;
  }
}

.custom-popover {
  z-index: 9999 !important;
  position: fixed !important;
}

::v-deep .custom-popover {
  z-index: 9999 !important;
}

::v-deep .el-select-dropdown {
  z-index: 9999 !important;
}
</style>
